package com.geek.project.geekauth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.geek.project.geekauth.exception.AuthException;
import com.geek.project.geekauth.service.UserService;
import com.geek.project.geekauth.utils.IpUtils;
import com.geek.project.geekauthapi.model.vo.LoginVo;
import com.geek.project.geekauthapi.model.vo.UserVo;
import com.geek.project.geekauthstarter.service.JwtService;
import com.geek.project.geekverificationcodestarter.service.kaptcha.VerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl {

    @Autowired
    private VerifyCodeService verifyCodeService;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtService jwtService;

    public UserVo login(LoginVo user, HttpServletRequest request, HttpServletResponse response){
        UserVo vo = userService.findUserByAccount(user);
        if(ObjectUtil.isEmpty(vo)){
            throw new AuthException("账号不存在");
        }
        if(!vo.getPasswd().equals(user.getPassword())){
            throw new AuthException("账号或密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", vo.getId());
        map.put("nickname", vo.getName1());
        map.put("ip", IpUtils.getIpAddress(request));

        String token = jwtService.generateToken(map);
        response.setHeader("authorization", token);
        return vo;
    }

    public void logout(String token){
//        if (){
//
//        }
    }

    public void sendSms(String phone){
        if (StrUtil.isEmptyIfStr(phone)){
            throw new AuthException("请输入手机号码");
        }
        if(!PhoneUtil.isMobile(phone)) {
            throw new AuthException("请输入正确的手机号码");
        }
        verifyCodeService.generalPhoneVerifyCode(phone);

    }
}
